package com.lottery.common.util;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.lottery.common.dto.CqsscDTO;
import com.lottery.cqssc.service.CqsscService;

@Component
public class TimerThread extends Thread {
	private static Logger logger = Logger.getLogger(TimerThread.class);
	
	@Resource
	private CqsscService cqsscService;
	
	public void run() {
		while(true){
			String leftTime4CQSSC = (String) EhCacheUtils.get("leftTime4CQSSC");
			System.out.println("leftTime: " + leftTime4CQSSC);
			long leftTime = 0;
			try {
				if (StringUtils.isNotEmpty(leftTime4CQSSC)) {
					leftTime = Long.parseLong(leftTime4CQSSC);
				}
				if (leftTime-- > 0) {
					EhCacheUtils.put("leftTime4CQSSC", String.valueOf(leftTime));
					sleep(1000);
				} else {
					EhCacheUtils.put("leftTime4CQSSC", calcualteLeftTime());
				}
				
			} catch (Exception e) {
				logger.info(e);
			}
		}
	}
	
	private String getTimeIntervalFromProperties(String gameType) {
		String interval = StringUtils.EMPTY;
		Calendar today = Calendar.getInstance();
		Calendar todayAtEightClock = Calendar.getInstance();
		todayAtEightClock.set(Calendar.HOUR_OF_DAY, 8);
		todayAtEightClock.set(Calendar.MINUTE, 0);
		todayAtEightClock.set(Calendar.SECOND, 0);
		Calendar todayAtTwentyClock = Calendar.getInstance();
		todayAtTwentyClock.set(Calendar.HOUR_OF_DAY, 20);
		todayAtTwentyClock.set(Calendar.MINUTE, 0);
		todayAtTwentyClock.set(Calendar.SECOND, 0);
		logger.info("today: "+ today.getTime() + "  8 clock: " + todayAtEightClock.getTime() + 
				" 20 clock: " + todayAtTwentyClock.getTime());
		if (today.getTimeInMillis() >= todayAtEightClock.getTimeInMillis() &&
			today.getTimeInMillis() <= todayAtTwentyClock.getTimeInMillis()) {
			interval = PropertiesUtil.getDefaulSystemProperties().getProperty("day.time.interval");
		} else {
			interval = PropertiesUtil.getDefaulSystemProperties().getProperty("night.time.interval");
		}
		logger.info("interval: " + interval);
		return interval;
	}
	
	public String calcualteLeftTime() {
		long optInterval = Long.parseLong(this.getTimeIntervalFromProperties(""));
		CqsscDTO sqsscDto = this.cqsscService.queryLastestCqssc();
		long openTimestamp = Long.parseLong(sqsscDto.getOpentimestamp());
		long currentTimestamp = new Date().getTime();
		long optLeftTime = openTimestamp + optInterval - currentTimestamp / 1000;
		
		return String.valueOf(optLeftTime);
	}

}
